import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { Area } from 'src/merchant/area/area.schema'
import { Brand } from 'src/merchant/brand/brandschema'
import { Shop } from 'src/merchant/shop/shop.shcema'
import { Order } from 'src/order/order.schema'
import { Proudce } from 'src/Produce/Schema/produce.schema'

interface RequestBody {
  brand: string
  area: string
  shop: string
  date: string
}

@Injectable()
export class AnalysisService {
  constructor(
    @InjectModel('product') private ProduceModel: Model<Proudce>,
    @InjectModel('order') private OrderModel: Model<Order>,
    @InjectModel('shop') private ShopModel: Model<Shop>,
    @InjectModel('brand') private BrandModel: Model<Brand>,
    @InjectModel('area') private AreaModel: Model<Area>,
  ) {}

  async getTop10() {
    // 从订单中查询产品卖的最多的前10个
    // 1. 从订单中查询所有的订单
    const orders = await this.OrderModel.find()
    // 2. 遍历订单，将订单中的产品和数量存入一个对象中
    const products = {}
    orders.forEach((order) => {
      order.OrderDetails.forEach((product) => {
        if (products[product.ProductName]) {
          products[product.ProductName].sales += product.count
        } else {
          products[product.ProductName] = {
            ProductName: product.ProductName,
            sales: product.count,
          }
        }
      })
    })
    // 3. 将对象中的值转换为数组
    const productsArray = Object.values(products)
    // 4. 对数组进行排序
    productsArray.sort((a, b) => b['sales'] - a['sales'])
    // 5. 取出前10个
    const top10 = productsArray.slice(0, 10)
    // 6. 返回前10个
    return top10
  }
}
